package com.myspringsecurity.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.xml.crypto.Data;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Q大侠
 * @date ：Created in 2022/11/2 15:27
 * @description：jwt工具类
 * @modified By：
 * @version:
 */
public class JWTUtil {
    private String sign="mkq-aaa";

    //生成jwt的token
    public String createJWT(Map<String,Object> map){
        //头信息
        Map<String,Object> head=new HashMap<>();
        head.put("alg","HS256");
        head.put("typ","JWT");
        //颁发时间
        Date iat=new Date();
        //过期时间
        Calendar expire=Calendar.getInstance();
        expire.set(Calendar.SECOND,7280);
        Date expiresTime=expire.getTime();
        String token = JWT.create()
                //头信息
                .withHeader(head)
                //设置颁发时间
                .withIssuedAt(iat)
                //设置过期时间
                .withExpiresAt(expiresTime)
                //自定义内容
                .withClaim("loginInfo",map)
                //签名
                .sign(Algorithm.HMAC256(sign));
        return token;
    }
    //校验token是否有效
    public boolean verify(String token){
        //获取一个jwt校验对象
    JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
    try {
        build.verify(token);
        return true;
    }catch (Exception e){
        e.printStackTrace();
        return false;
    }
}
    //获取载荷内容
    public  Map<String,Object> jieXi(String token){
        //获取一个jwt校验对象
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        DecodedJWT verify = build.verify(token);
        Claim loginInfo = verify.getClaim("loginInfo");
        System.out.println("--------"+loginInfo.asString());
        return loginInfo.asMap();
    }
}
